import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation, Routes, Route } from 'react-router-dom';
import CaseManagement from '../pages/CaseManagement';
import CourseManagement from '../pages/CourseManagement';
import ProfileManagement from '../pages/ProfileManagement';
import CreateCourse from '../pages/CreateCourse';
import UploadCourse from '../pages/UploadCourse';
import EditCourse from '../pages/EditCourse';
import CreateCase from '../pages/CreateCase';
import EditCase from '../pages/EditCase';
import { userStorage } from '../utils/storage';
import './MainLayout.css';

function MainLayout() {
  const [userInfo, setUserInfo] = useState(null);
  const [currentTab, setCurrentTab] = useState('case');
  const [tabHistory, setTabHistory] = useState({
    case: '/main/case',
    course: '/main/course',
    profile: '/main/profile'
  });
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    // 获取用户信息（使用 storage.js 会自动检查过期时间）
    const info = userStorage.getUserInfo();
    if (info) {
      setUserInfo(info);
    }
  }, []);

  // 根据路由同步当前 tab 并记录路径
  useEffect(() => {
    const path = location.pathname;
    
    if (path.includes('/main/case') || path.includes('/main/create-case') || path.includes('/main/edit-case/')) {
      setCurrentTab('case');
      setTabHistory(prev => ({ ...prev, case: path }));
    } else if (path.includes('/main/course') || path.includes('/main/create-course') || path.includes('/main/upload-course')) {
      setCurrentTab('course');
      setTabHistory(prev => ({ ...prev, course: path }));
    } else if (path.includes('/main/profile')) {
      setCurrentTab('profile');
      setTabHistory(prev => ({ ...prev, profile: path }));
    }
  }, [location.pathname]);

  const tabs = [
    { key: 'case', label: '案例管理', path: '/main/case' },
    { key: 'course', label: '课程管理', path: '/main/course' },
    { key: 'profile', label: '个人管理', path: '/main/profile' }
  ];
  
  // 获取当前应该显示的页面
  const getCurrentPage = () => {
    const path = location.pathname;
    if (path.includes('/main/create-case')) return 'create-case';
    if (path.includes('/main/edit-case/')) return 'edit-case';
    if (path.includes('/main/create-course')) return 'create-course';
    if (path.includes('/main/upload-course')) return 'upload-course';
    if (path.includes('/main/edit-course/')) return 'edit-course';
    return currentTab; // 主tab页面
  };
  
  const currentPage = getCurrentPage();

  const handleTabClick = (key) => {
    // 使用记录的路径，而不是默认路径
    const targetPath = tabHistory[key];
    setCurrentTab(key);
    navigate(targetPath, { replace: true });
  };

  return (
    <div className="main-layout">
      <header className="header">
        <div className="header-content">
          <div className="logo">Care Spirit 管理系统</div>
          <div className="user-info">
            {userInfo && `${userInfo.nickName}，您好`}
          </div>
        </div>
      </header>
      
      <div className="tab-container">
        {tabs.map(tab => (
          <div
            key={tab.key}
            className={`tab-item ${currentTab === tab.key ? 'active' : ''}`}
            onClick={() => handleTabClick(tab.key)}
          >
            {tab.label}
          </div>
        ))}
      </div>

      <div className="content">
        {/* 主Tab页面和不需要URL参数的页面使用条件渲染保持状态 */}
        <div className="tab-content" style={{ display: currentPage === 'case' ? 'block' : 'none' }}>
          <CaseManagement />
        </div>
        <div className="tab-content" style={{ display: currentPage === 'course' ? 'block' : 'none' }}>
          <CourseManagement />
        </div>
        <div className="tab-content" style={{ display: currentPage === 'profile' ? 'block' : 'none' }}>
          <ProfileManagement />
        </div>
        <div className="tab-content" style={{ display: currentPage === 'create-case' ? 'block' : 'none' }}>
          <CreateCase />
        </div>
        <div className="tab-content" style={{ display: currentPage === 'create-course' ? 'block' : 'none' }}>
          <CreateCourse />
        </div>
        <div className="tab-content" style={{ display: currentPage === 'upload-course' ? 'block' : 'none' }}>
          <UploadCourse />
        </div>
        
        {/* 需要URL参数的页面使用路由渲染 */}
        {(currentPage === 'edit-course' || currentPage === 'edit-case') && (
          <div className="tab-content">
            <Routes>
              <Route path="edit-course/:courseId" element={<EditCourse />} />
              <Route path="edit-case/:caseId" element={<EditCase />} />
            </Routes>
          </div>
        )}
      </div>
    </div>
  );
}

export default MainLayout;

